package edu.swust.graduation_project.eauction.fragment

import android.app.Activity.RESULT_OK
import android.content.DialogInterface
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.annotation.Nullable
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.net.toUri
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.tencent.cos.xml.CosXmlService
import com.tencent.cos.xml.CosXmlServiceConfig
import com.tencent.cos.xml.exception.CosXmlClientException
import com.tencent.cos.xml.exception.CosXmlServiceException
import com.tencent.cos.xml.listener.CosXmlResultListener
import com.tencent.cos.xml.model.CosXmlRequest
import com.tencent.cos.xml.model.CosXmlResult
import com.tencent.cos.xml.transfer.COSXMLUploadTask.COSXMLUploadTaskResult
import com.tencent.cos.xml.transfer.TransferConfig
import com.tencent.cos.xml.transfer.TransferManager
import com.tencent.qcloud.core.auth.QCloudCredentialProvider
import com.tencent.qcloud.core.auth.ShortTimeCredentialProvider
import edu.swust.graduation_project.eauction.R
import edu.swust.graduation_project.eauction.activity.DeliveryListActivity
import edu.swust.graduation_project.eauction.activity.EditUserActivity
import edu.swust.graduation_project.eauction.activity.LoginActivity
import edu.swust.graduation_project.eauction.activity.MyBidedActivity
import jp.wasabeef.blurry.Blurry
import java.lang.Exception
import java.sql.Connection
import java.sql.DriverManager
import kotlin.concurrent.thread


class UserFragment : Fragment() {
    internal var userPhone: String? = null
    internal var userEmail: String? = null
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val view: View = inflater.inflate(R.layout.fragment_user, container, false)
        val mIvusericon = view.findViewById<ImageView>(R.id.iv_usericon)
        val mIvusericonBack = view.findViewById<ImageView>(R.id.iv_usericon_back)
        val mTvUserName = view.findViewById<TextView>(R.id.tv_username)
        val mBtnOutLogin = view.findViewById<Button>(R.id.btn_user_outlogin)
        val mBtnEdit = view.findViewById<Button>(R.id.btn_user_edit)
        val mBtnMyBided = view.findViewById<Button>(R.id.btn_user_mybided)
        val mBtnMyCreate = view.findViewById<Button>(R.id.btn_user_craetebided)
        val mBtnDelivery = view.findViewById<Button>(R.id.btn_user_delivery)
        val mSharedPreferences: SharedPreferences = requireContext().getSharedPreferences(
            "user",
            AppCompatActivity.MODE_PRIVATE
        )

        setIcon(mSharedPreferences.getString("username", ""), mIvusericon, mIvusericonBack)
        mTvUserName.text = mSharedPreferences.getString("username", "")

        //更换头像以及背景图
        mIvusericon.setOnClickListener {
            openAlbum()
        }

        //弹出AlertDialog以确认登出账号信息
        mBtnOutLogin.setOnClickListener {
            AlertDialog.Builder(requireContext()).setMessage("确定要登出吗?").setTitle("登出？")
                .setPositiveButton("登出", DialogInterface.OnClickListener { dialogInterface, i ->
                    startActivity(Intent(activity, LoginActivity::class.java))
                    activity?.finish()
                })
                .setNeutralButton("取消", null).create().show()

        }

        //跳转至EditUserActivity以修改个人信息
        mBtnEdit.setOnClickListener {
            startActivityForResult(Intent(activity, EditUserActivity::class.java), 10)
        }

        //跳转至MyBidedActivity以查看我参加的拍卖
        mBtnMyBided.setOnClickListener {
            val intent = Intent(activity, MyBidedActivity::class.java)
            intent.putExtra("flag", 1)
            startActivity(intent)
        }

        mBtnMyCreate.setOnClickListener {
            val intent = Intent(activity, MyBidedActivity::class.java)
            intent.putExtra("flag", 2)
            startActivity(intent)
        }

        mBtnDelivery.setOnClickListener {
            val intent = Intent(activity, DeliveryListActivity::class.java)
            startActivity(intent)
        }
        return view
    }


    private fun uploadCOS(url: String) {
        val secretId = "*" //永久密钥 secretId
        val secretKey = "*" //永久密钥 secretKey
        // keyDuration 为请求中的密钥有效期，单位为秒
        val myCredentialProvider: QCloudCredentialProvider =
            ShortTimeCredentialProvider(secretId, secretKey, 300)
        // 存储桶所在地域简称，例如广州地区是 ap-guangzhou
        val region = "ap-chengdu"
        // 创建 CosXmlServiceConfig 对象，根据需要修改默认的配置参数
        val serviceConfig = CosXmlServiceConfig.Builder()
            .setRegion(region)
            .isHttps(true) // 使用 HTTPS 请求, 默认为 HTTP 请求
            .builder()
        // 初始化 COS Service，获取实例
        val cosXmlService: CosXmlService = CosXmlService(
            context,
            serviceConfig, myCredentialProvider
        )
        // 初始化 TransferConfig，这里使用默认配置，如果需要定制，请参考 SDK 接口文档
        val transferConfig = TransferConfig.Builder().build()
        // 初始化 TransferManager
        val transferManager = TransferManager(
            cosXmlService,
            transferConfig
        )
        val mSharedPreferences: SharedPreferences = requireContext().getSharedPreferences(
            "user",
            AppCompatActivity.MODE_PRIVATE
        )
        // 存储桶名称，由bucketname-appid 组成，appid必须填入
        var bucket = "*"
        var cosPath = "user_icon/" + mSharedPreferences.getString(
            "username",
            ""
        ) + ".png" //对象在存储桶中的位置标识符，即称对象键

        //本地文件的绝对路径
        val srcPath: Uri = url.toUri()

        //若存在初始化分块上传的 UploadId，则赋值对应的 uploadId 值用于续传；否则，赋值 null
        var uploadId: String? = null
        // 上传文件
        val cosxmlUploadTask = transferManager.upload(
            bucket, cosPath,
            srcPath, uploadId
        )
        //上传结果回调
        cosxmlUploadTask.setCosXmlResultListener(object : CosXmlResultListener {
            override fun onSuccess(request: CosXmlRequest, result: CosXmlResult) {
                val uploadResult = result as COSXMLUploadTaskResult
                Log.d("COS", "上传成功")
                setIconMysql(
                    mSharedPreferences.getString(
                        "username",
                        ""
                    )
                )
            }

            // 如果您使用 kotlin 语言来调用，请注意回调方法中的异常是可空的，否则不会回调 onFail 方法，即：
            // clientException 的类型为 CosXmlClientException?，serviceException 的类型为 CosXmlServiceException?
            override fun onFail(
                request: CosXmlRequest,
                @Nullable clientException: CosXmlClientException?,
                @Nullable serviceException: CosXmlServiceException?
            ) {
                if (clientException != null) {
                    clientException.printStackTrace()
                } else {
                    serviceException!!.printStackTrace()
                }
            }
        })
    }

    private fun setIcon(userName: String?, imageView: ImageView, imageViewback: ImageView) {
        object : Thread() {
            override fun run() {
                val sqlSelect =
                    "SELECT * FROM `Account` WHERE user_name='$userName'"
                val cn: Connection = DriverManager.getConnection(
                    "*",
                    "*", "*"
                )
                val ps = cn.createStatement()
                val resultSet = ps!!.executeQuery(sqlSelect)
                resultSet.next()
                val flag = resultSet.getBoolean("user_icon_default")
                userPhone = resultSet.getString("user_phone")
                userEmail = resultSet.getString("user_email")
                view?.post {
                    if (userPhone.isNullOrBlank()) view?.findViewById<TextView>(R.id.tv_userphone)?.text =
                        "Null"
                    else view?.findViewById<TextView>(R.id.tv_userphone)?.text = userPhone
                    if (userEmail.isNullOrBlank()) view?.findViewById<TextView>(R.id.tv_useremail)?.text =
                        "Null"
                    else view?.findViewById<TextView>(R.id.tv_useremail)?.text = userEmail
                }
                ps.close()
                cn.close()
                view?.post {
                    run {
                        replaceImageview(flag, userName, imageView, imageViewback)
                    }
                }
                Log.d("isIconDefault", flag.toString())
            }
        }.start()
    }

    private fun replaceImageview(
        flag: Boolean,
        userName: String?,
        imageView: ImageView,
        imageViewback: ImageView
    ) {
        Log.d("isIconDefaultOut", flag.toString())
        if (flag) {
            Log.d("Glide", "默认头像")
            try {
                Glide.with(this)
                    .load("*")
                    .skipMemoryCache(true)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(object : CustomTarget<Drawable>() {
                        override fun onResourceReady(
                            resource: Drawable,
                            transition: Transition<in Drawable>?
                        ) {
                            imageView.background = resource
                            Blurry.with(context).radius(20).capture(imageView).into(imageViewback)
                        }

                        override fun onLoadCleared(placeholder: Drawable?) {
                        }
                    })

            } catch (e: Exception) {
                e.printStackTrace()
            }
        } else {
            Log.d("Glide", "用户头像")
            try {
                Glide.with(requireActivity())
                    .load(
                        "*" +
                                userName +
                                ".png"
                    )
                    .skipMemoryCache(true)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(object : CustomTarget<Drawable>() {
                        override fun onResourceReady(
                            resource: Drawable,
                            transition: Transition<in Drawable>?
                        ) {
                            imageView.background = resource
                            Blurry.with(context).radius(20).capture(imageView).into(imageViewback)
                        }

                        override fun onLoadCleared(placeholder: Drawable?) {

                        }
                    })
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

    }

    private fun openAlbum() {
        val intent = Intent()
        intent.type = "image/*"
        intent.action = "android.intent.action.GET_CONTENT"
        intent.addCategory("android.intent.category.OPENABLE")
        startActivityForResult(intent, 1)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            when (requestCode) {
                1 -> run {
                    data?.dataString?.let { Log.d("URL", it) }
                    uploadCOS(data?.data.toString())
                    val mIvusericon = view?.findViewById<ImageView>(R.id.iv_usericon)
                    val mIvusericonBack = view?.findViewById<ImageView>(R.id.iv_usericon_back)
                    val mSharedPreferences: SharedPreferences =
                        requireContext().getSharedPreferences(
                            "user",
                            AppCompatActivity.MODE_PRIVATE
                        )
                    if (mIvusericon != null && mIvusericonBack != null) {
                        setIcon(
                            mSharedPreferences.getString("username", ""),
                            mIvusericon,
                            mIvusericonBack
                        )
                    }
                }

            }
        } else {
            when (requestCode) {
                10 -> run {
                    fragmentManager?.beginTransaction()?.replace(R.id.fl_container, UserFragment())
                        ?.commitAllowingStateLoss()
                    Log.d("onActivityResult", "2")
                }
            }
        }
    }

    private fun setIconMysql(userName: String?) {
        thread {
            val sqlUpdate =
                "UPDATE `test_case`.`Account` SET `user_icon_default` = '0' WHERE `Account`.`user_name` = '$userName'"
            val cn: Connection = DriverManager.getConnection(
                "*",
                "*", "*"
            )
            val ps = cn.createStatement()
            ps.execute(sqlUpdate)
            ps.close()
            cn.close()
        }
    }
}